<template>
	<view class="page">
		<navBar color="#000" background="#e0dac9" :title="$t('WiFi.distribution.network')"></navBar>
		<view class="web-cont">
			<!-- 雷达扫码开始 -->
			<radar :imageUrl="imageUrl"></radar>
			<view class="web-text">
				<view>{{$t('Connect.password')}}</view>
			</view>
		</view>
		<view class="web-item">
			<view class="web-title flex">
				<view>{{$t('Discovering.network')}}</view>
				<uni-load-more class="icon-zq" :status="status" :content-text="contentText" :iconSize="18" />
			</view>
			<view class="">
				<view class="item-box" v-if="array.length!=0">
					<view class="item flex_s" @click="bindPickerChange(wifi)" v-for="(wifi,index) in array"
						:key="index">
						<view class="item-left">{{ wifi.SSID }}</view>
						<!-- <view class="item-right flex">
							<view>{{wifi.isProtected?"有密码":'无密码'}}</view>
						</view> -->
					</view>
				</view>
				<view v-else>
					<view class="box">
						<view class="input-box" style="border-bottom: 1rpx solid rgba(101, 101, 101, .2);">
							<input adjust-position type="text" v-model="ssid" :placeholder="$t('enterWfiName')" />
						</view>
						<view class="input-box">
							<input adjust-position type="text" v-model="password"
								:placeholder="$t('enterWfiPassword')" />
						</view>
					</view>
					<view class="item-right" @click="getitem">
						{{$t('home.btn-Confirm-appointment')}}
					</view>
				</view>
			</view>
			<!-- 	<view class="weui-form">
				<view class="weui-form__text-area">
					<view class="weui-form__title">xBlufi蓝牙配网{{version}}</view>
					<view class="weui-form__desc">设计理念：简单/快速上手</view>
				</view>
				<view class="weui-form__control-area">
					<view class="weui-cells__group weui-cells__group_form">
						<view class="weui-cells__title">需配置入网当前路由器SSID：{{ssid}}</view>
						<view class="weui-cells weui-cells_form">
							<view class="weui-cell">
								<picker @change="bindPickerChange" :value="index" :range="array">
									<view class="picker">
										Wi-Fi列表：{{array[index]}}
									</view>
								</picker>
							</view>
							<view class="weui-cell">
								<view class="weui-cell__hd"><label class="weui-label">密码：</label></view>
								<view class="weui-cell__bd">
									<input class="weui-input" :value="password" @input="bindPasswordInput" type="text"
										placeholder="在此输入路由器密码" />
								</view>
							</view>





							<view class="weui-cell">
								<view class="weui-cell__hd"><label class="weui-label">数据：</label></view>
								<view class="weui-cell__bd">
									<input class="weui-input" @input="bindCustomDataInput" type="text"
										placeholder="在此输入自定义数据" />
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="weui-form__tips-area">
					<label for="weuiAgree" class="weui-agree">
						<input id="weuiAgree" type="checkbox" class="weui-agree__checkbox" /><span
							class="weui-agree__text">{{connected?"蓝牙已连接":"蓝牙已断开"}}
						</span>
					</label>
				</view>
				<view class="weui-form__opr-area">
					<button @click="OnClickStart" :disabled="!isInitOK"
						type="primary">{{isInitOK?"开始配网并发送自定义数据":"设备初始化失败或非2.4G网络"}}</button>
				</view>

				<view class="weui-form__extra-area">
					<view class="weui-footer">
						<view class="weui-footer__links">
							<navigator href="javascript:void(0);" class="weui-footer__link">https://github.com/xuhongv
							</navigator>
						</view>
						<view class="weui-footer__text">Copyright ©2019 半颗心脏 ver{{version}}</view>
					</view>
				</view>
			</view> -->
		</view>
		<PopupInput ref="PopupInput" @confirm="OnClickStart" :title="title"></PopupInput>
	</view>
</template>

<script>
	import radar from '@/componets/radar.vue';
	import PopupInput from '@/componets/PopupInput.vue';
	import xBlufi from '@/utils/blufi/xBlufi.js'
	export default {
		components: {
			PopupInput,
			radar
		},
		data() {
			return {
				title: this.$t('Connect.password'),
				imageUrl: 'https://be.coucoq.cn/jueli/static/2025/01/07/65f82df0-96c5-4169-b1e0-e821b1c9cc8a.png', //wifi背景图
				version: '2.2',
				name: '',
				index: 0,
				array: [],
				connectedDeviceId: '',
				connected: true,
				deviceInfo: null,
				isInitOK: false,
				ssid: '',
				password: '',
				customData: '',
				isProtected: null,
			}
		},
		onShow: function(options) {
			this.initWifi()
		},

		onLoad: function(options) {
			var that = this
			this.initWifi()
			that.name = options.name
			that.connectedDeviceId = options.deviceId
			that.name = options.name
			// that.setData({
			// 	name: options.name,
			// 	connectedDeviceId: options.deviceId,
			// 	name: options.name
			// })
			xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
			xBlufi.notifyInitBleEsp32({
				deviceId: options.deviceId,
			})
			uni.showLoading({
				title: this.$t('Device.initialization.progress'),
			})
		},
		onUnload: function() {
			console.log("unload ")
			let that = this
			xBlufi.notifyConnectBle({
				isStart: false,
				deviceId: that.connectedDeviceId,
				name: that.name,
			});
			xBlufi.listenDeviceMsgEvent(false, that.funListenDeviceMsgEvent);
		},
		methods: {
			funListenDeviceMsgEvent: function(options) {
				console.log(options, 'optionsdevice')
				let that = this
				let ssid_arry = this.array;
				switch (options.type) {
					case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED:
						// that.setData({
						// 	connected: options.result
						// });
						that.connected = options.result

						if (!options.result) {
							uni.showModal({
								title: this.$t('Tips'),
								content: this.$t('device.disconnected'),
								showCancel: false, //是否显示取消按钮
								cancelText: this.$t('home.btn-cancel'),
								confirmText: this.$t('home.btn-Confirm-appointment'),
								success: function(res) {
									uni.switchTab({
										url: '/pages/home/home'
									});
								},
							})
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_CONNECT_ROUTER_RESULT:
						uni.hideLoading();
						if (!options.result) {

						}
						// uni.showModal({
						// 	title: this.$t('Tips'),
						// 	content: this.$t('cannot.DistributionNetworkFailure'),
						// 	showCancel: false, //是否显示取消按钮
						// 	cancelText: this.$t('home.btn-cancel'),
						// 	confirmText: this.$t('home.btn-Confirm-appointment'),
						// })
						else {
							if (options.data.progress == 100) {
								let ssid = options.data.ssid;
								uni.showModal({
									title: this.$t('Tips'),
									content: `${this.$t('connection.successful')}【${this.utf8to16(options.data.ssid)}】`,
									showCancel: false, //是否显示取消按钮
									cancelText: this.$t('home.btn-cancel'),
									confirmText: this.$t('home.btn-Confirm-appointment'),
									success: function(res) {
										if (res.confirm) {
											uni.setStorage({
												key: ssid,
												data: that.password
											})
											//判断是否为空
											if (that.customData) {
												//开始发送自定义数据，此方法可以在蓝牙连接esp设备之后，随时随地调用！
												xBlufi.notifySendCustomData({
													customData: that.customData,
												})
											}
											uni.reLaunch({
												url: '/pages/device/device'
											});


										}

									},
								})
							}
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
						console.log("收到设备发来的自定义数据结果：", (options.data))
						uni.showModal({
							title: '收到自定义设备数据',
							content: `【${options.data}】`,
							showCancel: false, //是否显示取消按钮
						})
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_CONNECT_NEAR_ROUTER_LISTS:
						console.log(options.data, 'lllllllllllllllllllllllllllllllllll')
						uni.hideLoading();
						if ('' === options.data.SSID)
							break;
						ssid_arry.push({
							SSID: options.data.SSID,
							isProtected: options.data.isProtected
						})
						// that.setData({
						// 	array: ssid_arry
						// })
						that.array = ssid_arry
						console.log(that.array, '这是wf列表吗')
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT:
						uni.hideLoading();
						console.log("初始化结果：", JSON.stringify(options))
						if (options.result) {
							console.log('初始化成功')
							xBlufi.notifySendGetNearRouterSsid()
							uni.showLoading({
								title: `${this.$t('wiFi.list')}...`,
							})
						} else {
							console.log('初始化失败')
							// that.setData({
							// 	connected: false
							// })
							that.connected = false
							uni.showModal({
								title: this.$t('Tips'),
								content: this.$t('Device.initialization.failed'),
								showCancel: false, //是否显示取消按钮
								success: function(res) {
									uni.switchTab({
										url: '/pages/home/home'
									});
								}
							})
						}
						break;
				}
			},
			hasChinese(str) {
				// 检测中文字符的 Unicode 范围
				return /[\u4e00-\u9fa5]/.test(str);
			},
			utf8to16(utf8Str) {
				var out = "";
				var i = 0;
				var c, c2, c3;

				while (i < utf8Str.length) {
					c = utf8Str.charCodeAt(i++); // 获取第一个字节

					// 1. 单字节字符 (0xxxxxxx)
					if (c < 0x80) {
						out += String.fromCharCode(c);
					}
					// 2. 双字节字符 (110xxxxx 10xxxxxx)
					else if (c >= 0xC0 && c < 0xE0) {
						c2 = utf8Str.charCodeAt(i++);
						out += String.fromCharCode(((c & 0x1F) << 6) | (c2 & 0x3F));
					}
					// 3. 三字节字符 (1110xxxx 10xxxxxx 10xxxxxx)
					else if (c >= 0xE0 && c < 0xF0) {
						c2 = utf8Str.charCodeAt(i++);
						c3 = utf8Str.charCodeAt(i++);
						out += String.fromCharCode(
							((c & 0x0F) << 12) |
							((c2 & 0x3F) << 6) |
							(c3 & 0x3F)
						);
					}
				}
				return out;
			},
			utf16to8(str) {
				var out, i, len, c;
				out = "";
				len = str.length;
				for (i = 0; i < len; i++) {
					c = str.charCodeAt(i);
					if ((c >= 0x0001) && (c <= 0x007F)) {
						out += str.charAt(i);
					} else if (c > 0x07FF) {
						out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
						out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
						out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
					} else {
						out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
						out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
					}
				}
				return out
			},
			getitem() {
				console.log(this.ssid, 'this.ssid')
				console.log(this.password, 'this.ssid')
				uni.showLoading({
					title: this.$t('Distribution.network'),
					mask: true
				})
				xBlufi.notifySendRouterSsidAndPassword({
					ssid: this.utf16to8(this.ssid),
					password: this.password
				})
				// if (this.isProtected && !pass) {
				// 	uni.showToast({
				// 		title: this.$t('password.empty'),
				// 		icon: 'none'
				// 	})
				// 	return;
				// }
			},

			OnClickStart: function(pass) {
				if (!this.ssid) {
					uni.showToast({
						title: `SSID${this.$t('Cannot.empty')}`,
						icon: 'none'
					})
					return
				}
				// if (this.isProtected && !pass) {
				// 	uni.showToast({
				// 		title: this.$t('password.empty'),
				// 		icon: 'none'
				// 	})
				// 	return;
				// }


				uni.showLoading({
					title: this.$t('Distribution.network'),
					mask: true
				})
				xBlufi.notifySendRouterSsidAndPassword({
					ssid: this.utf16to8(this.ssid),
					password: pass
				})
			},
			bindPasswordInput: function(e) {
				// this.setData({
				// 	password: e.detail.value
				// })
				this.password = e.detail.value
			},
			bindCustomDataInput: function(e) {
				// this.setData({
				// 	customData: e.detail.value
				// })
				this.customData = e.detail.value
			},
			initWifi() {

			},
			bindPickerChange: function(e) {


				console.log('picker发送选择改变，携带值为', e)

				// this.setData({
				// 	index: e.detail.value
				// })
				// this.index = e.detail.value


				console.log("ssid=>", e.SSID)
				// console.log("ssid=>", this.array[e.detail.value])

				let password = uni.getStorageSync(e.SSID)
				// let password = wx.getStorageSync(this.array[e.detail.value])

				console.log("password=>", password)
				console.log("password=>this.array[e.detail.value]", e.SSID)

				// this.setData({
				// 	ssid: this.data.array[e.detail.value],
				// 	isInitOK: true,
				// 	password: password == undefined ? "" : password
				// })
				this.ssid = e.SSID
				this.isProtected = e.isProtected
				this.isInitOK = true
				this.password = password == undefined ? "" : password
				this.$refs.PopupInput.open();

			},
		}
	}
</script>

<style lang="scss" scoped>
	button {
		width: 75%;
	}

	.web-cont {
		background: #E0DAC9;

		.web-text {
			line-height: 49rpx;
			font-size: 30rpx;
			text-align: center;
			margin-top: 80rpx;
		}
	}

	.web-item {
		background-image: linear-gradient(to bottom, #E0DAC9, rgba(243, 238, 230, 0.1));
		margin: auto;
		padding: 50rpx 0;
		font-size: 30rpx;

		.web-title {
			width: 90%;
			margin: 20rpx auto;

			.icon-zq {
				margin-left: 10rpx;
			}
		}

		.item-box {
			width: 90%;
			margin: auto;
			background: #fff;
			border-radius: 15rpx;

			.item {
				line-height: 100rpx;
				border-bottom: 1rpx solid #f5f5f5;
				padding: 0 40rpx;
				color: #666666;
			}

			.item-left {}




		}
	}

	.box {
		background-color: #fff;
		margin: 30rpx;
		border-radius: 15rpx;
	}

	.input-box {
		padding: 30rpx;

	}

	.item-right {
		color: #fff;
		background-color: #af9453;
		text-align: center;
		padding: 20rpx;
		margin: 30rpx;
		border-radius: 15rpx;
	}
</style>